package com.hxd.otc.utils;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;

import com.app.hubert.guide.util.LogUtil;

import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.List;
import java.util.UUID;

import okhttp3.ResponseBody;

/**
 * 类  名 :  FileUtils
 * 作  者 :  胡庆岭
 * 时  间 :  2018/4/25 10:24
 * 描  述 :  ${文件工具类}
 */
public final class FileUtils {
    private static final String FILE_HOST = "WOTC";
    private static final String CACHE = "Cache";
    public static final String CAMERA = "camera";
    public static final String DOWNLOAD = "download";
    public static final String DOWNLOAD_PDF = "pdf";

    /**
     * 获取头部文件
     *
     * @param context 上下文
     * @return 返回文件
     */
    public static File getBaseFile(@NonNull Context context) {
        File baseFile;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            baseFile = Environment.getExternalStorageDirectory();
        } else {
            baseFile = context.getFilesDir();
        }
        baseFile = new File(baseFile.getAbsolutePath(), FILE_HOST);
        createFile(baseFile);
        return baseFile;
    }

    /**
     * 创建一个文件夹
     *
     * @param context
     * @param directoryName
     * @return
     */
    public static File outDirectory(@NonNull Context context, String directoryName) {
        File bodyFile = getBaseFile(context);
        bodyFile = new File(bodyFile.getAbsolutePath(), directoryName);
        createFile(bodyFile);
        return bodyFile;
    }

    /**
     * 创建一个图片文件
     *
     * @param context
     * @param directoryName
     * @return
     */
    public static File outImageFile(@NonNull Context context, String directoryName) {
        File file = outDirectory(context, directoryName);
        file = new File(file.getAbsolutePath(), System.currentTimeMillis() + ".jpg");
        return file;
    }

    /**
     * 缓存数据文件夹
     *
     * @param context 上下文
     * @return 返回文件夹
     */
    public static File getCacheFile(@NonNull Context context) {
        File baseFile = getBaseFile(context);
        baseFile = new File(baseFile.getAbsolutePath(), FileUtils.CACHE);
        createFile(baseFile);
        return baseFile;
    }

    /**
     * 创建文件夹
     *
     * @param file 文件夹
     */
    private static void createFile(@NonNull File file) {
        if (!file.exists() || !file.isDirectory()) {
            file.mkdirs();
        }
    }

    public static boolean isImageFile(File file) {
        if (file != null && file.exists() && file.isFile()) {
            String imagePath = file.getAbsolutePath();
            if (imagePath.endsWith(".jpg") || imagePath.endsWith(".jpeg") || imagePath.endsWith(".png") ||
                    imagePath.endsWith(".bmp") || imagePath.endsWith(".webp")) {
                return true;
            }
        }
        return false;
    }

    public static Uri fileToUri(@NonNull Context context, @NonNull File file, @NonNull Intent intent) {
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            String authority = context.getPackageName() + ".provider";
            uri = FileProvider.getUriForFile(context, authority, file);
            List<ResolveInfo> resolveInfos = context.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
            if (resolveInfos != null && resolveInfos.size() > 0)
                for (ResolveInfo resolveInfo : resolveInfos) {
                    String packageName = resolveInfo.activityInfo.packageName;
                    context.grantUriPermission(packageName, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                }
        } else {
            uri = Uri.fromFile(file);
        }
        return uri;
    }

    public static Uri fileToUri(@NonNull Context context, @NonNull File file) {
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            String authority = context.getPackageName() + ".provider";
            uri = FileProvider.getUriForFile(context, authority, file);
            /*ContentValues contentValues = new ContentValues(1);
            contentValues.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
            uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);*/
        } else {
            uri = Uri.fromFile(file);
        }


        return uri;
    }


    public static void scanImage(@NonNull Context context, @NonNull File file) {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            MediaScanner ms = new MediaScanner(context, file);
//            ms.refresh();
//        } else {
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        intent.setData(Uri.fromFile(file));
        context.sendBroadcast(intent);
//        }
    }

    public static String getFileName(String pathandname) {

//        int start = pathandname.lastIndexOf("/");
//        int end = pathandname.lastIndexOf(".");
//        if (start != -1 && end != -1) {
//            return UUID.randomUUID().toString() + "_" + pathandname.substring(start + 1, end);
//        } else {
//            return null;
//        }
        return UUID.randomUUID().toString() + ".jpg";
    }

    public static Bitmap getHttpBitmap(String url) {
        Bitmap bitmap = null;
        try {
            URL pictureUrl = new URL(url);
            InputStream in = pictureUrl.openStream();
            bitmap = BitmapFactory.decodeStream(in);
            in.close();
        } catch (Exception e) {
            bitmap = null;
            e.printStackTrace();
        }
        return bitmap;
    }

    public static void close(Closeable c) {
        if (c != null) {
            try {
                c.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    //下载文件，并保存到目标文件中
    public static boolean downloadAndSave(ResponseBody body, String fileName) {

        try {
            File destDir = new File(getBaseFile(UIUtils.getContext()).getAbsolutePath());
            if (!destDir.exists()) {
                destDir.mkdirs();
            }
            File downloadFile = FileUtils.outDirectory(UIUtils.getContext(), FileUtils.DOWNLOAD_PDF);
            downloadFile = new File(downloadFile.getAbsoluteFile(), fileName + ".pdf");

            InputStream inputStream = null;
            OutputStream outputStream = null;

            try {
                byte[] fileReader = new byte[1024 * 4];
                long fileSize = body.contentLength();//文件总长度
                long fileSizeDownloaded = 0;//已下载的文件长度
                inputStream = body.byteStream();
                outputStream = new FileOutputStream(downloadFile);
                LogUtil.e("开始保存到本地");

                while (true) {
                    int read = inputStream.read(fileReader);
                    if (read == -1) {
                        break;
                    }

                    outputStream.write(fileReader, 0, read);
                    fileSizeDownloaded += read;

                    LogUtil.e("保存进度：" + fileSizeDownloaded + "/" + (fileSize == -1 ? "未知长度" : fileSize));
                }

                outputStream.flush();
                return true;
            } catch (IOException e) {
                LogUtils.e("===IOException==========" + e.getMessage());
                e.printStackTrace();
                return false;
            } finally {
                if (inputStream != null)
                    inputStream.close();

                if (outputStream != null)
                    outputStream.close();
            }

        } catch (IOException e) {
            LogUtils.e("===IOException==========" + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

}
